package com.example.web;

import java.io.IOException;
import java.util.zip.GZIPOutputStream;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class CompressionFilter implements Filter {

	private ServletContext ctx; 
	private FilterConfig cfg;
	
	@Override
	public void init(FilterConfig cfg) throws ServletException {
		// TODO Auto-generated method stub
		this.cfg  = cfg; 
		ctx = cfg.getServletContext();
		ctx.log(cfg.getFilterName() + " initialized.");
		
		System.out.println("필터 이름 가져와서 저장 " +cfg.getFilterName().toString());
		
	}

	@Override
	public void doFilter(ServletRequest req, ServletResponse res,
			FilterChain fc) throws IOException, ServletException {
		// TODO Auto-generated method stub
		HttpServletRequest request = (HttpServletRequest) req;
		HttpServletResponse response = (HttpServletResponse) res;

		String valid_encodings = request.getHeader("Accept-Encoding");
		if(valid_encodings.indexOf("gzip") > -1){
			CompressionResponseWrapper wrappedResp = new CompressionResponseWrapper(response);
			
			wrappedResp.setHeader("Content-Encoding", "gzip");
			
			fc.doFilter(request, wrappedResp);
		
			GZIPOutputStream gzos = wrappedResp.getZipOutputStream();
			gzos.flush();
			
			ctx.log(cfg.getFilterName() + " finished request.");
		}
		else{
			ctx.log(cfg.getFilterName() + " no encoding performed.");
			
		
		}
	}


	
	@Override
	public void destroy() {
		// TODO Auto-generated method stub
		cfg = null;
		ctx = null;
	}
}
